package com.easy.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.easy.entity.Bills;
import com.easy.entity.Detail;
import com.easy.entity.Owner;
import com.easy.entity.Servernum;
import com.easy.entity.Sysstate;
import com.easy.entity.User;
import com.easy.service.ApiService;
import com.easy.service.BillService;
import com.easy.service.DetailService;
import com.easy.service.ManagerService;
import com.easy.service.UserService;
import com.easy.utils.ApiUtils;
import com.easy.utils.Page;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("/manager")
public class ManagerController {

	@Autowired
	private ManagerService managerService;
	@Autowired
	private DetailService detailService;
	@Autowired
	private UserService userService;
	@Autowired
	private ApiService apiService;
	@Autowired
	private BillService billService;

	@RequestMapping(value = "/login.htm", method = RequestMethod.POST)
	public String login(String username, String password, HttpSession session, Model model) {
		String psw = new Md5Hash(password, "jianzhi").toString();
		Subject subject = SecurityUtils.getSubject();
		String urn = "manager-" + username;
		UsernamePasswordToken token = new UsernamePasswordToken(urn, psw);
		try {
			subject.login(token);
			Owner owner = managerService.getOwnerByUsername(username);
			model.addAttribute("user", owner);
			session.setAttribute("userinfo", owner);
			return "redirect:/manager/index.htm";
		} catch (Exception e) {
			model.addAttribute("msg", "好好想一下你的管理员密码哦！！！");
			return "manager/login";
		}
	}

	@RequestMapping("/index.htm")
	public String index(HttpSession session, Model model) {
		Owner user = (Owner) session.getAttribute("userinfo");
		List<Detail> successlist = detailService.getAllDetailByContent("success");
		List<Detail> failedlist = detailService.getAllDetailByContent("failed");
		List<Detail> banlist = detailService.getAllDetailByContent("ban");

		model.addAttribute("success", successlist.size());
		model.addAttribute("failed", failedlist.size());
		model.addAttribute("ban", banlist.size());
		model.addAttribute("user", user);
		return "manager/index";
	}

	@RequestMapping("/user.htm")
	public String user(Integer pagenow, String mobile, Model model) {
		List<User> users = new ArrayList<>();
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		if (mobile == null || mobile.isEmpty()) {
			Page page = new Page(userService.getUserCount(), pagenow);
			users = userService.getUsersListByPage(pagenow, 20);
			model.addAttribute("users", users);
			model.addAttribute("page", page);
		} else {
			User userByMobile = userService.getUserByMobile(mobile);
			users.add(userByMobile);
			model.addAttribute("users", users);
			model.addAttribute("mobile", mobile);
		}
		return "manager/userlist";

	}

	@RequestMapping("/deleteuser.htm")
	public String deleteuser(Integer uid, Integer pagenow, Model model) {
		userService.deleteUser(uid);
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		Page page = new Page(userService.getUserCount(), pagenow);
		List<User> users = userService.getUsersListByPage(pagenow, 20);
		model.addAttribute("users", users);
		model.addAttribute("page", page);
		return "manager/userlist";
	}

	@RequestMapping("/detail.htm")
	public String detail(Integer pagenow, String mobile,Model model) {
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		List<Detail> details = new ArrayList<>();
		if (mobile == null || mobile.isEmpty()) {
			Page page = new Page(detailService.getDetailsCount(), pagenow);
			details = detailService.getDetailsListByPage(pagenow, 20);
			model.addAttribute("details", details);
			model.addAttribute("page", page);
		} else {
			Detail detailByMobile = detailService.getDetailByMobile(mobile);
			details.add(detailByMobile);
			model.addAttribute("details", details);
			model.addAttribute("mobile", mobile);
		}
		
		return "manager/detaillist";

	}

	@RequestMapping("/flushdetail.htm")
	public String flushdetail(Integer pagenow, Model model) {
		detailService.deleteAll();
		return "redirect:/manager/detail.htm";

	}

	@RequestMapping("/unlock.htm")
	public String unlock(Integer uid, Integer pagenow, Model model) {
		User userById = userService.getUserById(uid);
		userById.setBanflag((byte) 0);
		userService.updateUser(userById);
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		Page page = new Page(userService.getUserCount(), pagenow);
		List<User> users = userService.getUsersListByPage(pagenow, 20);
		model.addAttribute("users", users);
		model.addAttribute("page", page);
		return "manager/userlist";

	}

	@RequestMapping("/locked.htm")
	public String locked(Integer uid, Integer pagenow, Model model) {
		User userById = userService.getUserById(uid);
		userById.setBanflag((byte) 1);
		userService.updateUser(userById);
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		Page page = new Page(userService.getUserCount(), pagenow);
		List<User> users = userService.getUsersListByPage(pagenow, 20);
		model.addAttribute("users", users);
		model.addAttribute("page", page);
		return "manager/userlist";

	}

	@RequestMapping("/resetpwd.htm")
	public String resetpwd(Integer uid, Integer pagenow, Model model) {
		User userById = userService.getUserById(uid);
		userById.setPassword(new Md5Hash("000000", "jianzhi").toString());
		userService.updateUser(userById);
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		Page page = new Page(userService.getUserCount(), pagenow);
		List<User> users = userService.getUsersListByPage(pagenow, 20);
		model.addAttribute("users", users);
		model.addAttribute("page", page);
		model.addAttribute("msg", "密码重置成功");
		return "manager/userlist";

	}

	@RequestMapping("/detailsee.htm")
	public String detailsee(Integer did, Model model) {
		Detail detail = detailService.getDetailById(did);
		User user = userService.getUserById(detail.getUserid());
		model.addAttribute("user", user);
		model.addAttribute("detail", detail);
		return "manager/detailsee";

	}

	@RequestMapping("/sysset.htm")
	public String sysset(Model model) {
		Sysstate sysstate = managerService.getSysstate();
		model.addAttribute("sys", sysstate);
		return "manager/sysstate";

	}

	@RequestMapping("/savesys.htm")
	public String savesys(Sysstate sys, Model model) {
		managerService.updateSysstate(sys);
		if (sys.getWorking().equals("1")) {
			apiService.refreshLogin();
		}
		Sysstate sysstate = managerService.getSysstate();
		model.addAttribute("sys", sysstate);
		return "manager/sysstate";
	}

	@RequestMapping("/detailcheck.htm")
	public String detailcheck(Integer pagenow, Model model) {
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		Page page = new Page(detailService.getDetailsCheckedCount(1), pagenow);
		
		List<Detail> detaillist = detailService.getAllDetailByCheckedByPage(1, pagenow, 20);

		model.addAttribute("page", page);
		model.addAttribute("details", detaillist);
		return "manager/detailcheck";

	}

	@RequestMapping("/tasksuccess.htm")
	public String tasksuccess(Integer did, Model model) {
		Detail detailById = detailService.getDetailById(did);
		detailById.setCheckflag(2);
		detailById.setContent("success");
		detailById.setSuretime(new Date());
		detailService.updateDetail(detailById);
		return "redirect:/manager/detailcheck.htm";
	}

	@RequestMapping("/taskfailed.htm")
	public String taskfailed(Integer did, Model model) {
		Detail detailById = detailService.getDetailById(did);
		detailById.setCheckflag(3);
		detailById.setContent("ban");
		detailById.setSuretime(new Date());
		// 如果用户出现异常操作，错误的点击成功，则失败的同时封禁账号
		User userById = userService.getUserById(detailById.getUserid());
		userById.setBanflag((byte) 1);
		userService.updateUser(userById);
		detailService.updateDetail(detailById);
		return "redirect:/manager/detailcheck.htm";

	}

	@RequestMapping("/adduserpage.htm")
	public String adduser() {
		return "manager/adduser";
	}

	@RequestMapping("/adduser.htm")
	public String add(User user, Model model) {
		if (StringUtils.isNullOrEmpty(user.getMobile())) {
			model.addAttribute("msg", "手机号码不能为空！");
			return "manager/adduser";
		}
		if (StringUtils.isNullOrEmpty(user.getZhifubao())) {
			model.addAttribute("msg", "支付宝不能为空！");
			return "manager/adduser";
		}
		User userByMobile = userService.getUserByMobile(user.getMobile());
		if (userByMobile != null) {
			model.addAttribute("msg", "当前账号已经存在，请勿重新添加！");
			return "manager/adduser";
		}

		user.setJointime(new Date());
		user.setBanflag((byte) 0);
		user.setRolename("user");
		user.setPassword(new Md5Hash("000000", "jianzhi").toString());
		userService.addUser(user);
		return "manager/index";
	}

	@RequestMapping("/refreshtoken.htm")
	public String refreshtoken() {
		apiService.refreshLogin();
		return "manager/index";
	}

	@RequestMapping(value = "/pwdpage.htm")
	public String pwdpage(Model model, HttpSession session) {
		Owner user = (Owner) session.getAttribute("userinfo");
		model.addAttribute("user", user);
		return "manager/changepwd";
	}

	@RequestMapping(value = "/changepwd.htm")
	public String changepwd(String pwd, Model model, HttpSession session) {
		Owner owner = (Owner) session.getAttribute("userinfo");
		owner.setPassword(new Md5Hash(pwd, "jianzhi").toString());
		managerService.updateOwner(owner);
		model.addAttribute("msg", "密码更改成功！请重新登录！");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "manager/login";
	}

	@RequestMapping(value = "/showdetails.htm")
	public String showdetails(Integer uid, Model model) {
		List<Detail> detaiListByUserId = detailService.getDetaiListByUserId(uid);
		User userById = userService.getUserById(uid);
		model.addAttribute("detaillist", detaiListByUserId);
		model.addAttribute("user", userById);
		return "manager/usertasks";
	}

	@RequestMapping(value = "/summoney.htm")
	public String summoney(Model model) {
		List<User> cansum = new ArrayList<>();
		List<User> all = userService.getAll();
		for (User user : all) {
			if (detailService.finishToday(user)) {
				cansum.add(user);
			}
		}
		model.addAttribute("userlist", cansum);
		return "manager/summoneylist";
	}

	@RequestMapping(value = "/givemoneypage.htm")
	public String givemoneypage(Integer uid, Model model) {
		List<Detail> moneylist = new ArrayList<>();
		User user = userService.getUserById(uid);
		List<Detail> detaiListByUserId = detailService.getDetaiListByUserId(uid);
		for (Detail d : detaiListByUserId) {
			if (d.getCheckflag() == 2 && d.getContent().equals("success")) {
				moneylist.add(d);
			}
		}
		model.addAttribute("details", moneylist);
		model.addAttribute("user", user);
		return "manager/givemoney";
	}

	@RequestMapping(value = "/givemoney.htm")
	public String givemoney(Integer uid, String billtype, String money, Model model, HttpSession session) {
		Owner owner = (Owner) session.getAttribute("userinfo");
		List<Detail> moneylist = new ArrayList<>();
		User user = userService.getUserById(uid);
		List<Detail> detaiListByUserId = detailService.getDetaiListByUserId(uid);
		for (Detail d : detaiListByUserId) {
			if (d.getCheckflag() == 2 && d.getContent().equals("success")) {
				d.setCheckflag(4);
				detailService.updateDetail(d);
				billService.detailToBill(d, owner.getId(), billtype, money);
			}
		}
		model.addAttribute("details", moneylist);
		model.addAttribute("user", user);
		return "redirect:/manager/billlist.htm";
	}

	@RequestMapping(value = "/billlist.htm")
	public String billlist(Integer pagenow, Model model) {
		if (pagenow == null || pagenow < 0) {
			pagenow = 1;
		}
		Page page = new Page(userService.getUserCount(), pagenow);
		List<Bills> billListByPage = billService.getBillListByPage(pagenow, 20);
		model.addAttribute("bills", billListByPage);
		model.addAttribute("page", page);
		return "manager/billlist";
	}

	@RequestMapping(value = "/servermunlist.htm")
	public String servermunlist(Model model) {
		List<Servernum> serverList = managerService.getAllList();
		model.addAttribute("serverlist", serverList);
		return "manager/servernumlist";
	}

	@RequestMapping(value = "/changeserverstate.htm")
	public String servermunlist(Integer sid, String state, Model model) {
		Servernum serverNumById = managerService.getServerNumById(sid);
		serverNumById.setIsban(state);
		if (state.equals("0")) {
			String result = ApiUtils.getLogin(serverNumById.getApinum(), serverNumById.getApipwd());
			String[] login = result.split("\\|");
			if (login[0].equals("1")) {
				serverNumById.setToken(login[1]);
				serverNumById.setTokentime(new Date());
			} else {
				serverNumById.setIsban("1");
				serverNumById.setToken("notoken");
			}
		}
		managerService.updateServerNum(serverNumById);
		return "redirect:/manager/servermunlist.htm";
	}

	@RequestMapping(value = "/deleteservernum.htm")
	public String deleteservernum(Integer sid, Model model) {
		managerService.deleteServernum(sid);
		return "redirect:/manager/servermunlist.htm";
	}

	@RequestMapping(value = "/addservernum.htm")
	public String addservernum(String apinum, String apipwd, String isban, Model model) {
		Servernum num = new Servernum();
		num.setApinum(apinum);
		num.setApipwd(apipwd);
		num.setInusing((byte) 0);
		num.setCreatetime(new Date());
		num.setIsban(isban);
		if (isban.equals("0")) {
			String result = ApiUtils.getLogin(apinum, apipwd);
			String[] login = result.split("\\|");
			if (login[0].equals("1")) {
				num.setIsban("0");
				num.setToken(login[1]);
				num.setTokentime(new Date());
			} else {
				num.setIsban("1");
				num.setToken("notoken");
			}
		} else {
			num.setToken("notoken");
		}
		managerService.addServernum(num);
		return "redirect:/manager/servermunlist.htm";
	}

	@RequestMapping(value = "/changeuserpage.htm")
	public String servermunlist(Integer uid, Model model) {
		User userById = userService.getUserById(uid);
		model.addAttribute("user", userById);
		return "manager/changeuser";
	}

	@RequestMapping(value = "/saveuser.htm")
	public String saveuser(User user, Model model) {
		userService.updateUser(user);
		return "redirect:/manager/user.htm";
	}

	@RequestMapping(value = "/changesuccess.htm")
	public String changesuccess(Integer did, Integer pagenow, Model model) {
		Detail detail = detailService.getDetailById(did);
		detail.setCheckflag(2);
		detail.setState("1");
		detail.setCheckflag(2);
		detail.setSuretime(new Date());
		detail.setContent("success");
		detailService.updateDetail(detail);
		return "redirect:/manager/detail.htm?pagenow=" + pagenow;
	}

	@RequestMapping(value = "/deletedetail.htm")
	public String deletedetail(Integer did, Integer pagenow, Model model) {
		detailService.deleteDetail(did);
		return "redirect:/manager/detail.htm?pagenow=" + pagenow;
	}

}
